import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  // 实现 ExceptionFilter 接口的 catch 方法，用于捕获和处理异常
  catch(exception: HttpException, host: ArgumentsHost) {
    console.log(111333);
    // 获取请求和响应对象
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    // 获取异常的 HTTP 状态码
    const status = exception.getStatus();
    // 构建自定义错误响应对象
    const errorResponse = {
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      error: exception.message || 'Internal server error',
    };
    // 将自定义错误响应对象返回给客户端
    response.status(status).json(errorResponse);
  }
}
